#include <stdlib.h>
#include <string.h>
#include "symbols_table.h"

#define SIZE 911

TABLE_ENTRY *symbolsTable[SIZE];

void table_initialization()
{
        int i;
        for(i = 0; i < SIZE; ++i)
                symbolsTable[i] = 0;
}

TABLE_ENTRY* insert_entry(int token, char *name)
{
        int address;
        TABLE_ENTRY *entry;

        if(entry = find_entry(name))
                return entry;

        entry = (TABLE_ENTRY*)malloc(sizeof(TABLE_ENTRY));
        entry->token = token;
        entry->name = (char*)calloc(strlen(name)+1,sizeof(char));
        strcpy(entry->name, name);
        entry->next = 0;
        
        address = hash_address(name);
        entry->next = symbolsTable[address];
        symbolsTable[address] = entry;   
        
        return entry; 
}

int hash_address(char *name)
{
        int i;
        int address=1;
        int name_length = strlen(name);
        for(i = 0; i < name_length; ++i)
        {
                address = (address * name[i]) % SIZE + 1;       
        } 
        return address - 1;
}

TABLE_ENTRY* find_entry(char *name)
{
        int address;
        TABLE_ENTRY *sought_entry;

        address = hash_address(name);

        sought_entry = symbolsTable[address];
        while(sought_entry && strcmp(sought_entry->name, name) != 0) sought_entry = sought_entry->next;
        
        return sought_entry;     
}

void print_table()
{
        int i;
        TABLE_ENTRY *aux;
        for(i = 0; i < SIZE; ++i){
                aux = symbolsTable[i];
                while(aux != 0) {
                        printf("%d %s\n", aux->token, aux->name);
                        aux = aux->next;
                }
        }
}
